import serial
import rtoml
import glob
import sys
import os


def get_serial_ports():
    if sys.platform.startswith("win"):
        ports = ["COM%s" % (i + 1) for i in range(256)]
    elif sys.platform.startswith("linux") or sys.platform.startswith("cygwin"):
        # this excludes your current terminal "/dev/tty"
        ports = glob.glob("/dev/tty[A-Za-z]*")
    elif sys.platform.startswith("darwin"):
        ports = glob.glob("/dev/tty.*")
    else:
        raise EnvironmentError("Unsupported platform")

    result = []
    for port in ports:
        try:
            s = serial.Serial(port)
            s.close()
            result.append(port)
        except (OSError, serial.SerialException):
            pass
    return result


def get_camera_list():
    cameras = []
    for device in os.listdir("/dev"):
        if device.startswith("video"):
            cameras.append(os.path.join("/dev", device))
    return cameras


def read_settings():
    if os.path.exists("settings.toml"):
        with open("settings.toml", "r") as f:
            return rtoml.load(f)["setting"]
    else:
        default_settings = {
            "setting": {
                "serial_port": "/dev/ttyS8",
                "camera_index": "",
                "first_player": "造物",
                "user_color": "黑子",
            }
        }
        with open("settings.toml", "w") as f:
            rtoml.dump(default_settings, f)
        return default_settings["setting"]


def save_settings(settings):
    if os.path.exists("settings.toml"):
        with open("settings.toml", "r") as f:
            current_settings = rtoml.load(f)
    else:
        current_settings = {"setting": {}}

    current_settings["setting"].update(settings)

    with open("settings.toml", "w") as f:
        rtoml.dump(current_settings, f)
